HTML5 JS fillRect()奇怪的行为 [英] HTML5 JS fillRect() strange behavior

查看:136
本文介绍了HTML5 JS fillRect()奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在填充(x,y,宽度,高度)时遇到两个奇怪的问题。

I'm having two odd problems with fillrect(x, y, width, height).


  1. 正在乘以两个高度的值

  1. Is multiplying the value of "height" by two

X和y应设置为鼠标位置,但矩形偏离左下方,并得到当鼠标移动到左下角时,距离更远。

X and y is supposed to be set to the mouse position, but the rectangle is off to the bottom left, and gets further away as the mouse moves to the bottom left.

此代码来自视频教程,代码似乎为这个家伙和视频以及其他所有人工作,因为没有人评论过同样的问题。无论如何这里是代码:

This code is from a video tutorial, and the code seems to work for the guy and the video, and everyone else since no one commented having the same problem. Anyways here is the code:

function doFirst(){
    canv = document.getElementById('canvas');
    canvas = canv.getContext('2d');

    document.addEventListener("mousemove", onMouseMove, false);
}

function onMouseMove(e){
    canvas.clearRect(0, 0, canv.width, canv.height);
    var x = e.clientX;
    var y = e.clientY;
    canvas.fillRect(x, y, 50, 50);
}

window.addEventListener("load", doFirst, false);

我想也许我错过了教程中的一个步骤,经过一遍又一遍的检查后我决定简化它只是在没有鼠标监听器的情况下绘制一个矩形,但画布仍然以2倍高度和约2倍y位置绘制它。

I thought maybe I missed a step in the tutorial, and after checking over and over I decided to simplify it to just drawing a rectangle without the mouse listener, yet the canvas still drew it with 2X the height and about 2x the y position.

function doFirst(){
    canv = document.getElementById('canvas');
    canvas = canv.getContext('2d');

    canvas.fillRect(10, 10, 50, 50);
}

window.addEventListener("load", doFirst, false);

当我第一次开始玩HTML5画布时,fillRect函数工作正常,那么什么发生了什么?我怎么打破它?

The fillRect function was working fine just the other day when I first started playing with HTML5 canvas, so what happened? how did I break it?

推荐答案

我相信这是因为您尝试使用CSS设置画布的宽度和高度:

I believe this happens because you're trying to set the width and height of the canvas with CSS:

<!--Sets size of the canvas on the page-->
<canvas id="canvas" style="width:500px; height:500px;"></canvas>

相反,请使用:

<!--Sets drawing surface size-->
<canvas id="canvas" width="500" height="500"></canvas>

width和height属性表示绘图表面的大小,默认情况下是300x150。设置画布的CSS宽度和高度将扩展或缩小绘图表面,但不会更改曲面中的像素数。 fillRect 在绘图表面像素中采用
坐标,而不是HTML页面像素。

The "width" and "height" attributes indicate the size of the drawing surface, which by default is 300x150. Setting the CSS width and height of the canvas will expand or shrink the drawing surface, but will not change the number of pixels in the surface. fillRect takes coordinates in "drawing surface" pixels, not "HTML page pixels".

这篇关于HTML5 JS fillRect()奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆