簡體   English   中英

調整畫布大小后,在畫布上的鼠標位置獲取顏色

[英]Get color at mouse position in a canvas after having resized the canvas

調整canvas大小后,我無法在當前的鼠標光標位置獲得正確的顏色。 調整canvas大小的原因是使其適應不同的屏幕尺寸。 不幸的是,顏色數據在調整大小后無法更新。 我怎樣才能解決這個問題?

我的代碼在JS Fiddle上 (JS部分也在下面)。

您可以在此視頻中看到有關該問題的演示。

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;
}

問題是您正在縮放畫布。 您將必須設置其實際寬度和高度,然后重新繪制它。

檢查一下: http : //jsfiddle.net/vyjwLfuc/

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM