如何移动画布元素

How to move canvas elements?

本文关键字:元素 布元素 何移 动画      更新时间:2023-09-26

如何将第一个带有黑色填充的元素移动到鼠标光标?或者只是如何将它移动到事件处理程序中我的位置?

Javascript:

var drawing = document.getElementById('canvas');
var ctx = drawing.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(188, 50, 200, 100);
ctx.fillStyle = 'yellow';
ctx.fillRect(0, 0, 200, 100);
document.onmousemove = function(e) {
    /* How to move rectangle here? */
}

http://jsfiddle.net/9545qbo4/1/

提前谢谢。

我认为这在画布上是不可能的,但您的函数可以这样做:

ctx.clearRect(/* Old rect position */); 
ctx.fillRect(/* New rect position*/);

编辑:这里也有同样的问题。