Canvas中拖动时图像闪烁。

5

我正在画布内拖动一张图片。但在拖动过程中,图片会闪烁。我认为这是函数调用上存在的问题。我已经使用了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>
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
7
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);
};

那么你的意思是这种解决方案会出现闪烁问题!!!代码没问题!! - MJQ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,