关于截取部分图像显示demo,有兴趣可以把玩一下~~

来源:2-2 Canvas基础 玩转drawImage的参数

前端小蜗牛_

2017-07-22 21:41

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

*{margin: 0;padding: 0;}

canvas{display: block;border:solid 1px grey;margin: 50px auto;}

</style>

</head>

<body>

<canvas id="canvas"></canvas>

<script>

var canvas = document.getElementById('canvas');

var cxt = canvas.getContext('2d');

var image = new Image();

var image_bak = new Image();

window.onload = function(){

canvas.width = 800;

canvas.height = 400;

image.src = 'kn1.jpg';

image_bak.src = 'kn1.jpg';

image.onload = function(){

cxt.drawImage(image,0,0);

}

clip();

}

function clip(){

canvas.onmousedown = function(event){


event.stopPropagation();

var downX = event.clientX - canvas.getBoundingClientRect().left;

var downY = event.clientY - canvas.getBoundingClientRect().top;


this.onmousemove = function(e){

var curX = e.clientX - canvas.getBoundingClientRect().left;

var curY = e.clientY - canvas.getBoundingClientRect().top;


if(curX-downX<0 && curY-downY<0){

dx =  downX - curX;

dy =  downY - curY;

drawImage(cxt,image,curX,curY,dx,dy,500,0,dx,dy);

}else {

drawImage(cxt,image,downX,downY,curX-downX,curY-downY,500,0,curX-downX,curY-downY);

}

drawRect(cxt,downX,downY,curX-downX,curY-downY)


this.onmouseup = function(event){

this.onmousemove = null;

}


}

}

}

function drawImage(cxt,obj,sx,sy,dw,dh,dx,dy,dw,dh){

cxt.clearRect(0,0,canvas.width,canvas.height);

cxt.drawImage(image,0,0);

cxt.drawImage(obj,sx,sy,dw,dh,dx,dy,dw,dh);

}

function drawRect(cxt,x,y,w,h){

cxt.strokeStyle = 'red';

cxt.strokeRect(x,y,w,h);

}

</script>

</body>

</html>


写回答 关注

1回答

  • 高jay
    2017-08-11 13:55:00

    good

Canvas玩转图像处理

canvas系列第三课,学会编写图像算法,一起玩转图像处理吧

60328 学习 · 124 问题

查看课程

相似问题