【问题标题】:Not able to set background image in canvas无法在画布中设置背景图像
【发布时间】:2018-09-04 18:39:02
【问题描述】:

我正在尝试设置背景图像,在其上我可以拖动不同的形状以突出显示背景图像中的不同区域。 但我只能看到其中的任何一个,无论是形状还是图像。 以下是我的代码:

1)detailground函数负责绘制背景图片。 2) 3 个圆形对象的数组,创建圆形并将其渲染到画布上。 3) 三个鼠标事件及其对应的函数。

我尝试将draw函数传递给detailground,以便可以在图像上绘制圆圈。但是有些方法,我只能看到其中任何一个。 `

//track mouse position on mousemove
var mousePosition;
//track state of mousedown and up
var isMouseDown;

//reference to the canvas element
var c = document.getElementById("mycanvas");
c.width = window.innerWidth * 0.75;
c.height = window.innerHeight * 0.75;
//reference to 2d context
var ctx = c.getContext("2d");

//add listeners
document.addEventListener('mousemove', move, false);
document.addEventListener('mousedown', setDraggable, false);
document.addEventListener('mouseup', setDraggable, false);

//make some circles
var c1 = new Circle(50, 50, 50,  "black");
var c2 = new Circle(200, 50, 50, "green", "black");
var c3 = new Circle(350, 50, 50, "blue", "black");
//initialise our circles
var circles = [c1, c2, c3];
drawbackground(c, ctx, draw);
draw(c, ctx);
function drawbackground(c, ctx, onload){
    var imagePaper = new Image();
    imagePaper.onload = function(){
    	ctx.drawImage(imagePaper,100, 20, 500,500);
    	onload(c, ctx);
    };
	 imagePaper.src = "https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg";
}

//main draw method
function draw(c, ctx) {
    //clear canvas
    ctx.clearRect(0, 0, c.width, c.height);
    drawCircles();
}

//draw circles
function drawCircles() {
    for (var i = circles.length - 1; i >= 0; i--) {
        circles[i].draw();
    }
}

//key track of circle focus and focused index
var focused = {
    key: 0,
    state: false
}

//circle Object
    function Circle(x, y, r, fill, stroke) {
        this.startingAngle = 0;
        this.endAngle = 2 * Math.PI;
        this.x = x;
        this.y = y;
        this.r = r;

        this.fill = fill;
        this.stroke = stroke;

        this.draw = function () {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.r, this.startingAngle, this.endAngle);
           // ctx.fillStyle = this.fill;
            ctx.lineWidth = 3;
           // ctx.fill();
            ctx.strokeStyle = this.stroke;
            ctx.stroke();
        }
    }

    function move(e) {
        if (!isMouseDown) {
            return;
        }
        getMousePosition(e);
        //if any circle is focused
        if (focused.state) {
            circles[focused.key].x = mousePosition.x;
            circles[focused.key].y = mousePosition.y;
            draw(c, ctx);
            return;
        }
        //no circle currently focused check if circle is hovered
        for (var i = 0; i < circles.length; i++) {
            if (intersects(circles[i])) {
                circles.move(i, 0);
                focused.state = true;
                break;
            }
        }
        draw(c, ctx);
    }

    //set mousedown state
    function setDraggable(e) {
        var t = e.type;
        if (t === "mousedown") {
            isMouseDown = true;
        } else if (t === "mouseup") {
            isMouseDown = false;
            releaseFocus();
        }
    }

    function releaseFocus() {
        focused.state = false;
    }

    function getMousePosition(e) {
        var rect = c.getBoundingClientRect();
        mousePosition = {
            x: Math.round(e.x - rect.left),
            y: Math.round(e.y - rect.top)
        }
    }

    //detects whether the mouse cursor is between x and y relative to the radius specified
    function intersects(circle) {
        // subtract the x, y coordinates from the mouse position to get coordinates 
        // for the hotspot location and check against the area of the radius
        var areaX = mousePosition.x - circle.x;
        var areaY = mousePosition.y - circle.y;
        //return true if x^2 + y^2 <= radius squared.
        return areaX * areaX + areaY * areaY <= circle.r * circle.r;
    }

Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
};
draw(c, ctx);
&lt;canvas id="mycanvas" style="border:1px solid red;" &gt;&lt;/canvas&gt;

`

这里是小提琴的链接: https://jsfiddle.net/y9fr1q7n/101/

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    你有很多不必要的代码(我把它留给你让它变得更好)。

    问题出在detailground函数中,因为每次鼠标移动时您都在等待img加载,并且draw函数出现问题,因为当您清除画布时,您不会重绘img

    //track mouse position on mousemove
    var mousePosition;
    //track state of mousedown and up
    var isMouseDown;
    
    //reference to the canvas element
    var c = document.getElementById("mycanvas");
    c.width = window.innerWidth * 0.75;
    c.height = window.innerHeight * 0.75;
    //reference to 2d context
    var ctx = c.getContext("2d");
    
    //add listeners
    document.addEventListener('mousemove', move, false);
    document.addEventListener('mousedown', setDraggable, false);
    document.addEventListener('mouseup', setDraggable, false);
    
    //make some circles
    var c1 = new Circle(50, 50, 50,  "black");
    var c2 = new Circle(200, 50, 50, "green", "black");
    var c3 = new Circle(350, 50, 50, "blue", "black");
    //initialise our circles
    var circles = [c1, c2, c3];
    var imagePaper = new Image();
    imagePaper.src = "https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg";
    imagePaper.onload = function(){
        draw(c, ctx);
    };
    
    function drawbackground(c, ctx, onload){
        ctx.drawImage(imagePaper,100, 20, 500,500);
    }
    
    //main draw method
    function draw(c, ctx) {
        //clear canvas
        ctx.clearRect(0, 0, c.width, c.height);
        drawbackground(c, ctx, draw);
        drawCircles();
    }
    
    //draw circles
    function drawCircles() {
        for (var i = circles.length - 1; i >= 0; i--) {
            circles[i].draw();
        }
    }
    
    //key track of circle focus and focused index
    var focused = {
        key: 0,
        state: false
    }
    
    //circle Object
        function Circle(x, y, r, fill, stroke) {
            this.startingAngle = 0;
            this.endAngle = 2 * Math.PI;
            this.x = x;
            this.y = y;
            this.r = r;
    
            this.fill = fill;
            this.stroke = stroke;
    
            this.draw = function () {
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.r, this.startingAngle, this.endAngle);
               // ctx.fillStyle = this.fill;
                ctx.lineWidth = 3;
               // ctx.fill();
                ctx.strokeStyle = this.stroke;
                ctx.stroke();
            }
        }
    
        function move(e) {
            if (!isMouseDown) {
                return;
            }
            getMousePosition(e);
            //if any circle is focused
            if (focused.state) {
                circles[focused.key].x = mousePosition.x;
                circles[focused.key].y = mousePosition.y;
                draw(c, ctx);
                return;
            }
            //no circle currently focused check if circle is hovered
            for (var i = 0; i < circles.length; i++) {
                if (intersects(circles[i])) {
                    circles.move(i, 0);
                    focused.state = true;
                    break;
                }
            }
            draw(c, ctx);
        }
    
        //set mousedown state
        function setDraggable(e) {
            var t = e.type;
            if (t === "mousedown") {
                isMouseDown = true;
            } else if (t === "mouseup") {
                isMouseDown = false;
                releaseFocus();
            }
        }
    
        function releaseFocus() {
            focused.state = false;
        }
    
        function getMousePosition(e) {
            var rect = c.getBoundingClientRect();
            mousePosition = {
                x: Math.round(e.x - rect.left),
                y: Math.round(e.y - rect.top)
            }
        }
    
        //detects whether the mouse cursor is between x and y relative to the radius specified
        function intersects(circle) {
            // subtract the x, y coordinates from the mouse position to get coordinates 
            // for the hotspot location and check against the area of the radius
            var areaX = mousePosition.x - circle.x;
            var areaY = mousePosition.y - circle.y;
            //return true if x^2 + y^2 <= radius squared.
            return areaX * areaX + areaY * areaY <= circle.r * circle.r;
        }
    
    Array.prototype.move = function (old_index, new_index) {
        if (new_index >= this.length) {
            var k = new_index - this.length;
            while ((k--) + 1) {
                this.push(undefined);
            }
        }
        this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    };
    &lt;canvas id="mycanvas" style="border:1px solid red;" &gt;&lt;/canvas&gt;

    【讨论】:

    • 非常感谢您指出错误。您的代码对我有用,所以我将其标记为答案。我对画布绘图和图像处理非常陌生,并且被分配了一项任务来制作图像编辑器之类的东西。我不确定哪些代码是不必要的,但会尽量使其紧凑和可读。我将在评论部分复制更新的代码。请您验证一次。谢谢。
    • 到目前为止,我尽我最大的 JS 知识尝试清理代码。所以我删除了数组,因为我只需要向前移动一个圆圈。但是圆圈没有响应任何鼠标事件。我尝试调试代码,但无法弄清楚我做错了什么。下面是相同的小提琴链接。请你帮我指出我在这里犯的错误。 jsfiddle.net/d409kyz8/51
    • 你忘了做focused.state = truejsfiddle.net/d409kyz8/72
    • 谢谢叶甫根尼。你认为我里面还有不必要的代码吗?我必须在其中添加更多功能以满足业务需求。您能否建议我一些好的电子书或教程,我可以在其中找到诸如制作带有文本的动态可拖动箭头、多行文本区域、图像上的普通箭头以及将最终画布绘图作为图像保存到本地目录中的内容?我正在阅读的任何教程都仅涵盖画布图像处理的基础知识。我还是 JS 的初学者,目前正在阅读eloquentjavascript.net 的书和一些在线短视频教程。
    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多