- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个代码:
var img = document.createElement("img");
img.src = "Images/test.png";
console.log(img);
img.addEventListener("load", start(img));
它应该创建一个新图像并通过“start()”将其显示到 Canvas 元素内的图案上。但它显示一个绿色框而不是图像。让它工作的唯一方法是在 HTML 中定义具有相同源的图像。当我尝试使该图像不可见时, Canvas 上的图像也变得不可见。这很令人困惑,因为我的代码是为了创建一个新元素而编写的,但由于某种原因,它被绑定(bind)到页面上的现有元素。有什么办法可以解决这个问题吗?
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas Library</title>
</head>
<style type="text/css">
.invisible {
display: none;
}
</style>
<body>
<p id="text">Unknown</p>
<canvas width="400" height="400" id="canvas"></canvas>
<img src="Images/test.png" class="invisible"></img>
<script type="text/javascript">
var Canvas = document.getElementById("canvas");
var label = document.getElementById("text");
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
console.log("" + rgbToHex(255, 100, 50));
var distance = function(x1, y1, x2, y2) {
var a = Math.pow(x2 - x1, 2);
var b = Math.pow(y2 - y1, 2);
return Math.sqrt(a + b);
};
//Declare the Canvas Object
var canvasObj = function(src) {
//Function to see if a line is colliding with a certain point Has an accuracy of about 1 pixel
this.lineIsColliding = function(startX, startY, endX, endY, testX, testY) {
const v1 = {
x: endX - startX,
y: endY - startY
};
const l2 = v1.x * v1.x + v1.y * v1.y;
if (l2 === 0) {
return false;
} // line has no length so can't be near anything
const v2 = {
x: testX - startX,
y: testY - startY
};
const u = (v1.x * v2.x + v1.y * v2.y) / l2;
return u >= 0 && u <= 1 && Math.abs((v1.x * v2.y - v1.y * v2.x) / Math.sqrt(l2)) < 1;
};
var self = this;
//The Canvas to draw on
this.src = src;
//The context of source(used for drawing)
this.ctx = this.src.getContext("2d");
//The Mouse Move Function
this.showCoordinates = function(e) {
console.log(e);
label.innerHTML = "<b>x: </b>" + e.offsetX + " <b>y: </b>" + e.offsetY + ", " + self.lineIsColliding(358, 277, 365, 268, e.offsetX, e.offsetY);
};
//Show coordinates variable
this.showCoordinatesBool = true;
//The boolean to tell if we should use stroke
this.useStroke = true;
//The fill style and stroke style(can be color, pattern, or gradient)
this.fillStyle = "#000000";
this.strokeStyle = "#000000";
//The Line cap style (can be butt, square, or round)
this.lineCap = "butt";
//The Stroke Weight (how wide the strokes are)
this.strokeWeightVar = "default";
//The corner style (how the corners are drawn)
this.cornerStyle = "miter";
//The Shadow Color
this.shadowColorVar = "#000000";
//The shadow Blur
this.shadowBlurVar = 0;
//The shadow Offsets
this.shadowOffsetX = 0;
this.shadowOffsetY = 0;
//The style of the current font
this.fontStyle = "normal";
//The variant of the current font
this.fontVariant = "normal";
//The thickness of the current font
this.fontThickness = "normal";
//The height/size of the current font
this.fontSize = 10;
//The family of the current font
this.fontFamily = "sans-serif";
//Function to set the fill style
this.fill = function(style) {
this.fillStyle = style;
this.ctx.fillStyle = style;
};
//Function to set the stroke style
this.stroke = function(style) {
this.useStroke = true;
this.strokeStyle = style;
this.ctx.strokeStyle = style;
};
//Function to delete the stroke
this.noStroke = function() {
this.useStroke = false;
};
//Function to draw a rectangle
this.rect = function(x, y, width, height) {
this.ctx.fillRect(x, y, width, height);
if (this.useStroke) {
this.ctx.strokeRect(x, y, width, height);
}
};
//Function to draw a corner
this.corner = function(style, centerX, centerY, x1, y1, x2, y2) {
this.ctx.lineJoin = style;
this.cornerStyle = style;
this.ctx.beginPath();
this.ctx.moveTo(x1, y1);
this.ctx.lineTo(centerX, centerY);
this.ctx.lineTo(x2, y2);
this.ctx.stroke();
};
//Function to draw a hollow rectangle
this.hollowRect = function(x, y, width, height) {
this.ctx.strokeRect(x, y, width, height);
};
//Function to set the canvas background
this.background = function(style) {
this.fillStyle = style;
this.ctx.fillStyle = style;
this.ctx.fillRect(0, 0, this.src.width, this.src.height);
};
//Function to draw a line
this.line = function(startX, startY, endX, endY) {
this.ctx.beginPath();
this.ctx.moveTo(startX, startY);
this.ctx.lineTo(endX, endY);
this.ctx.stroke();
};
//Function to change line style
this.lineCap = function(mode) {
this.ctx.lineCap = mode;
this.lineCap = mode;
};
//Function to change stroke weight
this.strokeWeight = function(weight) {
this.useStroke = true;
this.ctx.lineWidth = weight;
this.strokeWeightVar = weight;
};
//Function to clear a certain area
this.clearArea = function(x, y, width, height) {
this.ctx.clearRect(x, y, width, height);
};
//Turn the show coordinate function on
this.enableCoordinates = function() {
this.showCoordinatesBool = true;
this.src.addEventListener("mousemove", this.showCoordinates);
};
/*Shadows*/
//Set the shadow color
this.shadowColor = function(color) {
this.shadowColorVar = color;
this.ctx.shadowColor = color;
};
//Set the shadow blur
this.shadowBlur = function(blur) {
this.shadowBlurVar = blur;
this.ctx.shadowBlur = blur;
};
//Set the shadow offset
this.shadowOffset = function(offsetX, offsetY) {
this.shadowOffsetX = offsetX;
this.shadowOffsetY = offsetY;
this.ctx.shadowOffsetX = offsetX;
this.ctx.shadowOffsetY = offsetY;
};
//Remove shadows
this.noShadow = function() {
this.shadowOffset(0, 0);
this.shadowColor("#000000");
this.shadowBlur(0);
};
//Function to see if a rectangle is colliding with a specific point
this.rectIsColliding = function(rectX, rectY, rectWidth, rectHeight, testX, testY) {
this.ctx.rect(rectX, rectY, rectWidth, rectHeight);
return this.ctx.isPointInPath(testX, testY);
};
//Function that returns a custom linear gradient
this.linearGradient = function(startX, startY, endX, endY, colorStops) {
var gradient = this.ctx.createLinearGradient(startX, startY, endX, endY);
for (var i = 0; i < colorStops.length; i++) {
gradient.addColorStop(colorStops[i].location, colorStops[i].color);
}
return gradient;
};
//Function that returns a custom radial gradient
this.radialGradient = function(x0, y0, r0, x1, y1, r1, colorStops) {
var radialGradientVar = this.ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
for (var i = 0; i < colorStops.length; i++) {
radialGradientVar.addColorStop(colorStops[i].location, colorStops[i].color);
}
return radialGradientVar;
};
//Function that allows you to create a pattern
this.pattern = function(image, mode) {
var pat = this.ctx.createPattern(image, mode);
return pat;
};
//Function that allows you to make text. Optional width parameter to limit the width of the text. Optional font parameter if you would like to set it manually.
this.text = function(text, x, y, width, font) {
if (font) {
this.ctx.font = font;
}
else {
this.ctx.font = this.fontStyle + " " + this.fontVariant + " " + this.fontThickness + " " + this.fontSize + "px " + this.fontFamily;
console.log(this.ctx.font);
console.log(this.fontStyle + " " + this.fontVariant + " " + this.fontThickness + " " + this.fontSize + "px " + this.fontFamily);
}
if (width) {
this.ctx.fillText(text, x, y, width);
if (this.useStroke) {
this.ctx.strokeText(text, x, y, width);
}
}
else {
this.ctx.fillText(text, x, y);
if (this.useStroke) {
this.ctx.strokeText(text, x, y);
}
}
};
//Function that allows you to make hollow text. Optional width parameter to limit the width of the text. Optional font parameter if you would like to set it manually. Font Size MUIST be an INTEGER if you do not specify the font parameter
this.hollowText = function(text, x, y, width, font) {
if (font) {
this.ctx.font = font;
}
else {
this.ctx.font = this.fontStyle + " " + this.fontVariant + " " + this.fontThickness + " " + this.fontSize + "px " + this.fontFamily;
console.log(this.ctx.font);
console.log(this.fontStyle + " " + this.fontVariant + " " + this.fontThickness + " " + this.fontSize + "px " + this.fontFamily);
}
this.ctx.strokeText(text, x, y, width);
};
this.textWidth = function(text) {
return this.ctx.measureText(text).width;
};
};
//The following code is for testing purposes ONLY!
var start = function(image) {
//Create a new canvas
var myCanvas = new canvasObj(Canvas);
//Set the Background Color
myCanvas.background("#ff0000");
//Set the fill color
myCanvas.fill("#0000ff");
//Set the Stroke Color
myCanvas.stroke("#00ff00");
//Draw a rectangle
myCanvas.rect(164, 153, 50, 100);
//Draw a hollow rectangle
myCanvas.hollowRect(300, 300, 50, 50);
//Disable the Stroke
myCanvas.noStroke();
//Draw a rectangle with no stroke
myCanvas.rect(21, 18, 50, 50);
//Change the Stroke color
myCanvas.stroke("#ffff00");
//Change the stroke weight
myCanvas.strokeWeight(10);
//Change the line cap
myCanvas.lineCap("round");
//Draw a line
myCanvas.line(350, 30, 250, 80);
//Draw a corner
myCanvas.corner("miter", 50, 135, 100, 185, 100, 110);
//Enable the Coordinates
myCanvas.enableCoordinates();
//Clear a space from the canvas
myCanvas.clearArea(6, 245, 100, 100);
//Set the Shadow Color
myCanvas.shadowColor("black");
//Set the shadow Blur
myCanvas.shadowBlur(20);
//Set the shadow offset
myCanvas.shadowOffset(10, 0);
//Set the stroke
myCanvas.noStroke();
//Set the fill color
myCanvas.fill("orange");
//Draw a rectangle
myCanvas.rect(268, 167, 30, 30);
//Remove the shadow
myCanvas.noShadow();
//Test if the rectangle is colliding with a specific point
if (myCanvas.rectIsColliding(268, 167, 30, 30, 290, 170)) {
myCanvas.fill("green");
myCanvas.rect(358, 0, 50, 46);
}
else {
myCanvas.fill("yellow");
myCanvas.rect(362, 0, 50, 46);
}
//Test if a line is colliding with a certain point
console.log("function returned: " + myCanvas.lineIsColliding(358, 277, 365, 268, 362, 271));
if (myCanvas.lineIsColliding(358, 277, 365, 268, 362, 271)) {
console.log("line is colliding!");
myCanvas.line(358, 277, 365, 268);
}
else {
console.log("line is not colliding!");
}
myCanvas.line(0, 0, 50, 10);
//Color stop used for creating gradients
var colorStop = function(location, color) {
this.location = location;
this.color = color;
};
console.log(distance(0, 0, 50, 10));
myCanvas.fill(myCanvas.linearGradient(259, 77, 359, 127, [new colorStop(0.0, "green"), new colorStop(1.0, "blue")]));
myCanvas.rect(259, 87, 100, 50);
myCanvas.fill(myCanvas.radialGradient(309, 225, 10, 309, 225, 50, [new colorStop(0.0, "yellow"), new colorStop(1.0, "green")]));
myCanvas.rect(259, 200, 100, 50);
var pattern = myCanvas.pattern(image, "repeat");
myCanvas.fill(pattern);
myCanvas.rect(132, 81, 50, 100);
myCanvas.fill(rgbToHex(0, 0, 0));
//Setup text
myCanvas.fontSize = 50;
myCanvas.fontStyle = "oblique";
myCanvas.fontVariant = "small-caps";
myCanvas.fontThickness = 900;
myCanvas.fontFamily = "sans";
//Draw text
myCanvas.text("Test", 200, 200);
console.log(myCanvas.textWidth("Test"));
};
var img = document.createElement("img");
img.src = "Images/test.png";
console.log(img);
img.addEventListener("load", start(img));
</script>
</body>
</html>
最佳答案
由于您立即执行了 start
函数,因此您尝试在加载 img
之前使用它。
使用
img.addEventListener("load", function(){start(img);});
换句话说,您需要将函数作为参数传递给 addEventListener
,但您改为调用函数并传递结果
关于JavaScript 从 HTML 中获取图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46653812/
我需要您在以下方面提供帮助。近一个月来,我一直在阅读有关任务和异步的内容。 我想尝试在一个简单的 wep api 项目中实现我新获得的知识。我有以下方法,并且它们都按预期工作: public Htt
我的可执行 jar 中有一个模板文件 (.xls)。不需要在运行时我需要为这个文件创建 100 多个副本(稍后将唯一地附加)。用于获取 jar 文件中的资源 (template.xls)。我正在使用
我在查看网站的模型代码时对原型(prototype)有疑问。我知道这对 Javascript 中的继承很有用。 在这个例子中... define([], function () { "use
影响我性能的前三项操作是: 获取滚动条 获取偏移高度 Ext.getStyle 为了解释我的应用程序中发生了什么:我有一个网格,其中有一列在每个单元格中呈现网格。当我几乎对网格的内容做任何事情时,它运
我正在使用以下函数来获取 URL 参数。 function gup(name, url) { name = name.replace(/[\[]/, '\\\[').replace(/[\]]/,
我最近一直在使用 sysctl 来做很多事情,现在我使用 HW_MACHINE_ARCH 变量。我正在使用以下代码。请注意,当我尝试获取其他变量 HW_MACHINE 时,此代码可以完美运行。我还认为
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 关闭 9 年前。 要求提供代码的问题必须表现出对所解决问题的最低限度的理解。包括尝试过的解决方案、为什么
由于使用 main-bower-files 作为使用 Gulp 的编译任务的一部分,我无法使用 node_modules 中的 webpack 来require 模块code> dir 因为我会弄乱当
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 5 年前。 Improve this qu
我使用 Gridlayout 在一行中放置 4 个元素。首先,我有一个 JPanel,一切正常。对于行数变大并且我必须能够向下滚动的情况,我对其进行了一些更改。现在我的 JPanel 上添加了一个 J
由于以下原因,我想将 VolumeId 的值保存在变量中: #!/usr/bin/env python import boto3 import json import argparse import
我正在将 MSAL 版本 1.x 更新为 MSAL-browser 的 Angular 。所以我正在尝试从版本 1.x 迁移到 2.X.I 能够成功替换代码并且工作正常。但是我遇到了 acquireT
我知道有很多关于此的问题,例如 Getting daily averages with pandas和 How get monthly mean in pandas using groupby但我遇到
This is the query string that I am receiving in URL. Output url: /demo/analysis/test?startDate=Sat+
我正在尝试使用 javascript 中的以下代码访问 Geoserver 层 var gkvrtWmsSource =new ol.source.ImageWMS({ u
API 需要一个包含授权代码的 header 。这就是我到目前为止所拥有的: var fullUrl = 'https://api.ecobee.com/1/thermostat?json=\{"s
如何获取文件中的最后一个字符,如果是某个字符,则删除它而不将整个文件加载到内存中? 这就是我目前所拥有的。 using (var fileStream = new FileStream("file.t
我是这个社区的新手,想出了我的第一个问题。 我正在使用 JSP,我成功地创建了 JSP-Sites,它正在使用jsp:setParameter 和 jsp:getParameter 具有单个字符串。
在回答 StoreStore reordering happens when compiling C++ for x86 @Peter Cordes 写过 For Acquire/Release se
我有一个函数,我们将其命名为 X1,它返回变量 Y。该函数在操作 .on("focusout", X1) 中使用。如何获取变量Y?执行.on后X1的结果? 最佳答案 您可以更改 Y 的范围以使其位于函
我是一名优秀的程序员,十分优秀!