使用canvas实现画图功能

原创 苏秦陶侃 随笔 html5 335阅读 2017-05-04 22:56:05 举报

/html代码/
<canvas id="mycanvas" width="500px" height="500px"></canvas>
//此处image标签中引入的图像作为绘制点
<img id="myimage" src="timg.jpg" style="display: none;">
<script type="text/javascript" src="canvas.js"></script>

/js代码/
//获取图片对象、画布对象,以及画布的上下文对象
var image = document.getElementById("myimage");
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
//设置初始值用来判断鼠标左键是否按下
var isDrawing = false;
//获取画布初始图像元素的数据
var state = ctx.getImageData(0,0,canvas.width,canvas.height);
//将初始图像元素数据放到history的栈中
history.pushState(state,null);
//阻止pointerdown事件
canvas.addEventListener("pointerdown",function(e){
e.preventManipulation()
},false);
//绘制图像
canvas.addEventListener("mousedown",startDrawing,false);
canvas.addEventListener("mousemove",draw,false);
canvas.addEventListener("mouseup",stopDrawing,false);
window.addEventListener("popstate",loadState,false);

function startDrawing(){
    isDrawing = true;
}

function draw(){
    if (isDrawing) {
        var sx = canvas.width / canvas.offsetWidth;
        var sy = canvas.height / canvas.offsetHeight;
        var x= sx * event.clientX - image.naturalWidth/2;
        var y = sy *event.clientY - image.naturalHeight/2;
        ctx.drawImage(image,x,y,10,10);
    }
}

function stopDrawing(){
    isDrawing = false;
    var state = ctx.getImageData(0,0,canvas.width,canvas.height);
    history.pushState(state,null);
}

function loadState(e) {
    ctx.clearRect(0,0,canvas.width,canvas.height);
    if(e.state){
        ctx.putImageData(e.state,0,0);
    }
}
评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复