在画布中拖动时图像闪烁 [英] Image flickers during drag in canvas

查看:107
本文介绍了在画布中拖动时图像闪烁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在画布中拖动图像。但在拖动图像期间闪烁。我认为函数调用存在一些问题。我已经使用onmousedown,onmouseup和onmousemove事件实现了函数。我在拖动过程中将图像绘制到画布上。

I am dragging an image within a canvas. But during the drag image flickers. I think there is some problem in function calling. I have implemented functions with onmousedown, onmouseup and onmousemove events. I am drawing the image onto canvas during drag.

这是我的代码,

<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 时,它会在绘制之前加载图像。当然,图像是缓存的,但这个过程需要时间。相反,在做任何事情之前等待图像加载,然后再从不加载它。

See what this does? Every time you call drawcan, it loads the image before painting it somewhen later. Of course, the image is cached, but this process needs its time. Instead, wait for the image to load before doing anything, and then never load it again.

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);
};

这篇关于在画布中拖动时图像闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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