【问题标题】:Get color at mouse position in a canvas after having resized the canvas调整画布大小后在画布中的鼠标位置获取颜色
【发布时间】:2015-12-02 21:34:21
【问题描述】:

调整canvas 的大小后,我无法在当前鼠标光标位置获得正确的颜色。 调整canvas 大小的原因是使其适应不同的屏幕尺寸。 不幸的是,颜色数据在调整大小后没有得到更新。 我该如何解决这个问题?

我的代码是on JS Fiddle(JS部分也在下面)。

您可以看到in this video 问题的演示。

var actualColor = "ffffff";
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

context.canvas.width = 150;
context.canvas.height = 200;
context.beginPath(); context.rect(0,0,150,100); context.fillStyle="red"; context.fill(); context.closePath();
context.beginPath(); context.rect(0,100,150,100); context.fillStyle="blue"; context.fill(); context.closePath();

window.addEventListener('load', function(){
    resize();
});

window.addEventListener('resize', function(){
    resize();
});


/**
 * Scale proportionally: If the width of the canvas > the height, the canvas height
 * equals the height of the browser window. Else, the canvas width equals the width of the browser window.
 * If the window is resized, the size of the canvas changes dynamically.
 */

function resize() {
    var ratio = canvas.width / canvas.height;
    var canvas_height = window.innerHeight;
    canvas_height -= 130; // remove later
    var canvas_width = canvas_height * ratio;
    if (canvas_width > window.innerWidth) {
        canvas_width = window.innerWidth;
        canvas_height = canvas_width / ratio;
    }
    canvas.style.width = canvas_width + 'px';
    canvas.style.height = canvas_height + 'px';
}


// get the color at the mouse position
$('#canvas').mousemove(function (e) {
    var pos = {
      x:canvas.offsetLeft,
      y:canvas.offsetTop
    }
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var c = canvas.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data;
    actualColor = ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#colorOutput').css("background-color", "#" + actualColor); 
    $('#status').html(actualColor);
});

function rgbToHex(r, g, b) {
    return componentToHex(r) + componentToHex(g) + componentToHex(b);
}

function componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}

【问题讨论】:

    标签: javascript canvas colors position


    【解决方案1】:

    问题是您正在缩放画布。您必须设置它的实际宽度和高度,然后重新绘制它。

    看看这个:http://jsfiddle.net/vyjwLfuc/

    function resize() {
        ...
        canvas.width = canvas_width
        canvas.height = canvas_height
        draw()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2020-12-23
      • 2010-11-10
      • 1970-01-01
      相关资源
      最近更新 更多