【发布时间】:2022-01-19 09:50:28
【问题描述】:
我正在做一个项目,其中我使用一张照片和一个画布元素来绘制它以了解这张照片中的颜色,问题是我只能用 300 像素的照片宽度和 300 像素的高度来执行此操作150 像素。如果我输入其他值,画布会缩放照片并且不允许我使用整个区域,我会留下附加代码和一些图像。问题是,如果我增加照片的尺寸和它缩放的画布的尺寸,只留下选择屏幕上显示的内容。
300x150 的图像 正确的图像
无效的图片:
糟糕的工作形象
var xInic, yInic;
let ptop = 0;
let pleft = 0;
var estaPulsado = false;
function ratonPulsado(evt) {
//Obtener la posición de inicio
xInic = evt.clientX;
yInic = evt.clientY;
estaPulsado = true;
//Para Internet Explorer: Contenido no seleccionable
document.getElementById("cuadro").unselectable = true;
}
function ratonMovido(evt, left_pos) {
if (estaPulsado) {
//Calcular la diferencia de posición
var xActual = evt.clientX;
var yActual = evt.clientY;
var xInc = xActual - xInic;
var yInc = yActual - yInic;
xInic = xActual;
yInic = yActual;
//Establecer la nueva posición
var elemento = document.getElementById("cuadro");
var position = getPosicion(elemento);
elemento.style.top = (position[0] + yInc) + "px";
elemento.style.left = (position[1] + xInc) + "px";
ptop = position[0] + yInc
pleft = position[1] + xInc
return ptop, pleft;
}
}
* {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.estiloCuadro {
width: 5px;
height: 5px;
border: solid red;
position: absolute;
cursor: pointer;
/*Deshabilitar selección de texto*/
}
body {
background: aqua;
}
/*img{
width: 150px;
}*/
h1 {
background: red;
width: 300px;
}
#what {
height: 150px;
width: 150px;
}
<img id="imagen_1" src="https://htmlcolorcodes.com/assets/images/html-color-codes-color-palette-generators-hero.jpg" height="150" width="300">
<span id="he"></span>
<div id="cuadro" class="estiloCuadro"></div>
<canvas id="canvas"></canvas>
<div id="color">
<h1>El color es: </h1><br>
<div id="what"></div>
<p id="rf"></p>
</div>
<script src="js/main.js" async></script>
【问题讨论】:
-
您必须通过
<canvas>element 的.height和.width属性更改“画布”(坐标空间)的大小。 "画布的显示大小可以使用 CSS 进行更改,但如果这样做图像在渲染过程中会缩放以适应样式大小,这可能会使最终的图形渲染最终失真。最好通过直接在 -
实际绘制图像的代码在哪里?
-
PS 你确定你需要支持 IE9 吗?今天我们使用 CSS
user-select: none;stackoverflow.com/questions/826782/… 而不是unselectable -
链接的 q/a 中没有遗漏的一点可能会让您感到困惑,那就是 drawImage 采用图像的固有大小并完全忽略了
width和height的元素。
标签: javascript html canvas