<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.cube{
height: 0;
width: 0;
position: absolute;
left: 0;
top:0;
border: 2px solid lightseagreen;
box-sizing: border-box;
background-image: url("img/web.png");
}
#big{
border: 1px solid black;
height: 500px;
width: 500px;
position: relative;
background-image: url("img/pixel.png");
line-height: 500px;
overflow: hidden;
vertical-align: middle;
text-align: center;
float: left;
}
#big>img{line-height: 500px; vertical-align: middle;
max-height: 100%;
max-width: 100%;
}
.cv{
position: relative;
float: left; border: 2px solid lightseagreen;
}
</style>
<script>
let count=0;let c,b,d,p1,p2,cv,cx,img,p;
window.onload=function (){
c=document.querySelector(".cube");
b=document.getElementById("big");
cv=document.getElementById("c");
cx=cv.getContext('2d');
img=new Image();
d=b.querySelector("img");
img.src=d.src;
img.onload=function(){
cx.drawImage(img, 0,0,500,500,0,0,500,500);
p=img.width/b.querySelector("img").width;
console.log(img);
}
p1={
x:0,
y:0
};
p2={
x:0,
y:0
};
b.addEventListener("click",function (e){
let l;
count++;
if(count===1){
p1.x=e.offsetX;
p1.y=e.offsetY;
if(e.target===d){
p1.y=p1.y+d.offsetTop;
p1.x=p1.x+d.offsetLeft;
}
c.style.left=p1.x+"px";
c.style.top=p1.y+"px";
console.log(p1);
}
if(count===2){
p2.x=e.offsetX;
p2.y=e.offsetY;
if(e.target===d){
p2.y=p2.y+d.offsetTop;
p2.x=p2.x+d.offsetLeft;
}
if(p2.x>c.offsetLeft){
c.style.width=(p2.x-c.offsetLeft)+'px';
}else{
l=c.offsetLeft;
c.style.left=p2.x+"px";
c.style.width=(l-p2.x)+'px';
}
if(p2.y>c.offsetTop){
c.style.height=(p2.y-c.offsetTop)+'px';
}else{
l=c.offsetTop;
c.style.top=p2.y+"px";
c.style.height=(l-p2.y)+'px';
}
myDraw();
}
});
}
function myDraw(){
cx.clearRect(0,0,500,500);
let w=p1.x-p2.x;
if(w<0){
w=-w;
}
w*=p;
let h=p1.y-p2.y;
if(h<0){
h=-h;
}
h*=p;
if(p1.x<p2.x){
p1.x=(p1.x-b.querySelector("img").offsetLeft)*p;
}else{
p1.x=(p2.x-b.querySelector("img").offsetLeft)*p;
}
if(p1.y<p2.y){
p1.y=(p1.y-b.querySelector("img").offsetTop)*p;
}else{
p1.y=(p2.y-b.querySelector("img").offsetTop)*p;
}
if(p1.x<=0){
p1.x=0;
}
if(p1.y<=0){
p1.y=0;
}
if(w>img.width){
w=img.width;
}
if(h>img.height){
h=img.height;
}
cx.drawImage(img,
p1.x,p1.y,
w,h,0,0,500,500);
p1.x=0;
p1.y=0;
p2.x=0;
p2.y=0;
}
</script>
</head>
<body >
<div
id="big">
<div class="cube">
</div>
<img src="img/katy2.jpg" alt=""/>
</div>
<div class="cv">
<canvas id="c" height="500" width="500">
</canvas>
</div>
</body>
</html>
JS实现图片切割
最新推荐文章于 2024-04-14 12:13:08 发布