javascript - 在框中重新定位图像

标签 javascript jquery css

<分区>


关闭 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/

上一篇:javascript - 展开可折叠的 div 后阻止 ui

下一篇:html - 如何让我的导航栏填满我的 div 的整个宽度

相关文章:

jquery - 为什么 Firefox 一直突出显示我的下拉菜单链接?可能与 CSS/JQuery 相关

javascript - 在页面加载时淡入 div

javascript - JS : enabling export/import on client side (ES6 or using babel)?

javascript - 布局组件(抽屉、工具栏等)不作为组件工作

jquery - clearInterval(timerId) 不起作用

html - 如何使按钮中的图标居中

javascript - 向文本框添加默认值

javascript - 如何删除这个 HTML?

javascript - 无法调用空 dhtmlx 网格的方法 'appendChild'

javascript - 元素淡出和淡入时如何保持DOM位置