簡體   English   中英

是否可以在Canvas中獲得位置,而Canvas是CSS固定元素?

[英]Is it possible to get position in Canvas where canvas is a css fixed element?

現在,當我設定位置時:絕對; 在CSS它給出:

Uncaught TypeError: Cannot read property 'x' of undefined
    at HTMLCanvasElement.getColor

當位置:絕對; 但是我需要固定位置的畫布。

我的findPos()函數獲取對象的位置:

 function findPos(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); return { x: curleft, y: curtop }; } return undefined; } 

請檢查小提琴以獲取我的代碼: https : //jsfiddle.net/ds6kug6r/8/

這是因為根據規范2.1 ),固定定位的元素沒有offsetParent元素。

但是無論如何您都不需要它,而是使用Element.getBoundingClientRect() ,它不會遭受填充邊問題的困擾。

 function getColor(e) { // getBoundingClientRect to retrieve the position of our canvas in the doc var rect = this.getBoundingClientRect(); // we also need to use clientX and clientY values now var x = e.clientX - rect.left; var y = e.clientY - rect.top; var coord = "x=" + x + ", y=" + y; var c = this.getContext('2d'); var p = c.getImageData(x, y, 1, 1).data; log(p); } /* Color Wheel */ var canvas = document.getElementById("picker"); var context = canvas.getContext("2d"); var x = canvas.width / 2; var y = canvas.height / 2; var radius = 100; var counterClockwise = false; for (var angle = 0; angle <= 360; angle += 1) { var startAngle = (angle - 2) * Math.PI / 180; var endAngle = angle * Math.PI / 180; context.beginPath(); context.moveTo(x, y); context.arc(x, y, radius, startAngle, endAngle, counterClockwise); var gradient = context.createRadialGradient(x, y, 0, x, y, radius); gradient.addColorStop(0, 'hsl(' + angle + ', 10%, 100%)'); gradient.addColorStop(1, 'hsl(' + angle + ', 100%, 50%)'); context.fillStyle = gradient; context.fill(); } document.getElementById("picker").addEventListener("click", getColor); function log(m) { document.getElementById("viz").style.backgroundColor = 'rgba(' + m + ')'; document.getElementById("log").append(m + '\\n') } 
 canvas { position: fixed; right: 10px; bottom: 10px; cursor: pointer; } #viz { display: inline-block; height: 20px; width: 20px; } 
 <canvas class="colorWheel" id="picker" width="200" height="200"></canvas> <div> Log: <span id="viz"></span> <pre id="log"></pre> </div> 

暫無
暫無

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

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