在画布中拖动时图像会闪烁
Image flickers during drag in canvas
我正在画布中拖动图像。但在拖动过程中,图像会闪烁。我认为函数调用中存在一些问题。我已经用onmousedown、onmouseup和onmousemove事件实现了功能。我正在拖动过程中将图像绘制到画布上。
这是我的代码,
<html>
<head>
</head>
<body>
<div>
<canvas id="canvas5" height="500" width="500" style = "position:relative;left:500px; border:2px solid black;"> This text is displayed if your browser does not support HTML5 Canvas. </canvas>
</div>
<script type="text/javascript">
var x2 = 100;
var y2 = 100;
var ctx;
var can;
var img=new Image();
function drawcan() {
can = document.getElementById("canvas5");
ctx = can.getContext('2d');
ctx.clearRect(0, 0, 500, 500);
img.onload = function(){
ctx.drawImage(img,x2 - img.width/2,y2 - img.height/2, img.width,img.height);
};
img.src="images/213.jpg";
};
function myMove(e){
x1 = e.pageX - x2 - can.offsetLeft;
x2 = x2 + x1;
y1 = e.pageY - y2 - can.offsetTop;
y2 = y2 + y1;
drawcan();
};
function myDown(e) {
if (e.pageX < x2 + img.width/2 + canvas5.offsetLeft)
if (e.pageX > x2 - img.width/2 + canvas5.offsetLeft)
if (e.pageY < y2 + img.height/2 + canvas5.offsetTop)
if (e.pageY > y2 - img.height/2 + canvas5.offsetTop){
can.onmousemove = myMove;
};
};
function myUp(e){
can.onmousemove = null;
};
drawcan();
can.onmousedown = myDown;
can.onmouseup = myUp;
</script>
</body>
</html>
function drawcan() {
can = document.getElementById("canvas5");
ctx = can.getContext('2d');
ctx.clearRect(0, 0, 500, 500);
img.onload = function(){
ctx.drawImage(img,x2 - img.width/2,y2 - img.height/2, img.width,img.height);
};
img.src="images/213.jpg";
};
看看这是怎么回事?每次调用drawcan
时,它都会加载图像,然后在稍后绘制。当然,图像是缓存的,但这个过程需要时间。相反,请等待图像加载后再执行任何操作,然后再也不要加载它。
var img = new Image(),
load = false,
can = document.getElementById("canvas5"),
ctx = can.getContext('2d');
img.onload = function() {
load = true;
drawcan(); // init
};
img.src="images/213.jpg";
function drawcan() {
if (!load) return;
ctx.clearRect(0, 0, 500, 500);
ctx.drawImage(img, x2 - img.width/2,y2 - img.height/2, img.width,img.height);
};
相关文章:
- 如何使用按键避免图像闪烁
- 使用setInterval()函数进行图像闪烁
- addClass,它更改bg图像,但在第一次加载时没有闪烁
- 悬停时setInterval中的图像闪烁
- 按下按钮时图像持续闪烁
- jQuery图像在悬停时闪烁
- 当使用MouseEvent将图像更改为其他图像时,如何避免闪烁
- 正在创建随机图像闪烁
- iOS 8中滚动时的背景图像闪烁问题
- Javascript-使图像出现,然后将其替换为另一个图像(闪烁)
- 如何在渲染Backbone视图时防止图像闪烁
- 无法使图像闪烁(得到)预期的错误
- 鼠标经过时图像闪烁
- Skrollr图像闪烁.Firefox预加载问题
- 防止在src更改时出现大图像闪烁
- 如何在Javascript中使图像闪烁和重叠
- 图像闪烁然后消失
- 图像闪烁ajax轮询
- 使用图像映射时,鼠标悬停上的图像闪烁javascript
- 从本地主机加载时图像闪烁