<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 8 年前。
标签 javascript jquery css
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 8 年前。
我需要一些指导来上传图像,然后提供拖动图像的功能,使其根据需要适合另一个图像形状。这是我到目前为止所拥有的:
http://goehints.com/public/ <--上传任何图像 点击提交后,我可以使用顶部图像进行选择和裁剪 - 但我想直接在六 Angular 形内调整大小/重新定位。有什么建议吗?
我相信所有的代码都可以从源码中看到,如果没有请告诉我,谢谢!
最佳答案
您可以只使用 Canvas 及其“剪辑”操作:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
var imgpos = { x:0, y:0, scale: 1.0 };
function redraw() {
canvas.width = canvas.width;
ctx.strokeStyle = "#000";
ctx.lineWidth = 4;
ctx.beginPath();
for (var i=0; i<6; i++) {
var t = 2*Math.PI*(i+0.5)/6;
var x = 200 + 200*Math.cos(t);
var y = 200 + 200*Math.sin(t);
if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
ctx.closePath();
ctx.save();
ctx.clip();
ctx.translate(imgpos.x, imgpos.y);
ctx.scale(imgpos.scale, imgpos.scale);
ctx.drawImage(img, 0, 0);
ctx.restore();
ctx.stroke();
ctx.fillStyle = "#F00";
}
我基本上是在绘制剪裁成六边形的图像,然后我也在绘制六边形边框。图像也是在应用平移/缩放变换后绘制的。
这允许您在页面中动态地进行所有缩放/裁剪,而无需在服务器端执行任何操作:
img.onload = redraw;
img.src = "cube.jpg";
var tracking = null;
canvas.onmousedown = function(event){
event.preventDefault(); event.stopPropagation();
var x = event.x, y = event.y;
canvas.onmousemove = function(event) {
event.preventDefault(); event.stopPropagation();
imgpos.x += event.x - x;
imgpos.y += event.y - y;
x = event.x; y = event.y;
redraw();
};
canvas.onmouseup = function() {
canvas.onmouseup = canvas.onmousemove = null;
};
};
canvas.onmousewheel = function(event) {
var d = event.wheelDelta;
while (d >= 120) {
imgpos.scale *= 1.1;
d -= 120;
}
while (d <= -120) {
imgpos.scale /= 1.1;
d += 120;
}
redraw();
};
您可以看到它正在运行 here .
关于javascript - 在框中重新定位图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27479002/