adding image to Javascript canvas using relative file path - javascript

I feel like there is a very simple way to do this, yet I can't find it. I have an image whose relative path to my clientscript.js file is ./images/orig classic pokemon frame.png. I want to draw it on the canvas, around the text that is drawn on the very last line of this code snippet:
function render(context) {
context.fillStyle = 'black';
context.strokeStyle = 'black';
context.save();
var imgFrame = new Image();
imgFrame.src = './images/origclassicpokemonframe.png';
imgFrame.onload = function(){
context.drawImage(imgFrame, 0, 0, 30,30);
};
context.font = "24px Early GameBoy";
context.fillText("What? _____", 10, canvasHeight-44); //20 padding plus 24 line height
The text shows up on the canvas, but the frame never does. Changing the dimensions or the x and y coordinates does not make a difference. Any help is appreciated.
EDIT: Changed the filepath to images/origclassicpokemonframe.PNG and now the image shows on canvas in firefox, but not chrome.
help????
Another edit: I can see in the console on both chrome and firefox that the HTTP request is loading it just fine but somehow it just doesn't want to draw on the canvas.

context isn't a global variable. As such, using it in the 'onload' function is out of it's scope.
There was nothing wrong with your src if it would work in an <img> element.

Related

Cropped image displayed with a weird 1px black border

EDIT: I've made a video showing the current issue. Recorded it on an old macbook so it took a while haha. Anyway, In the video you can see me uploading an image, cropping it and generating a pdf with it. The preview does not have a black border whatsoever, the pdf DOES have a black border. Hope this helped.
So I got a webapplication that lets the user upload a profile picture and later generate a pdf with the profile picture. The problem is that I would like to have the profile picture displayed with rounded corners / in a circle.
I am using jspdf to generate the pdf. With that library I can add an image with the addImage method, that takes a base64 encoded DataUrl. Unfortunately, there isn't a native method to display the image with rounded corners / in a circle, so I decided to let the user crop their image before encoding the url to base64. That's when the weird behavior starts... If the cropped image is displayed in a img tag, it's all good, a nice circle profile picture is displayed. When that dataUrl is used to generate a pdf, for some reason a 1px black border is generated around the image... If I inspect the dataurl in the browser or with a online base64 previewer, no black border is visible, only when it gets generated as a pdf...
For demonstration purposes I made a codesandbox. Images with a white background show the problem best. For example, use this image: profilepicture
This method is most likely what is causing the problem (I took this one directly from the cropperjs examples on github):
function getRoundedCanvas(sourceCanvas) {
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var width = sourceCanvas.width;
var height = sourceCanvas.height;
canvas.width = width;
canvas.height = height;
context.imageSmoothingEnabled = true;
context.drawImage(sourceCanvas, 0, 0, width, height);
context.globalCompositeOperation = "destination-in";
context.beginPath();
context.arc(
width / 2,
height / 2,
Math.min(width, height) / 2,
0,
2 * Math.PI,
true
);
context.fill();
return canvas;
}
This method is used in the crop method like this: roundedCanvas = getRoundedCanvas(croppedCanvas); If I take out that method and just use roundedCanvas = croppedCanvas; the image gets cropped to a square and is displayed without the black borders.
I have no idea how I can resolve this issue, and if it is even possible to resolve. Any help in the right direction is very much appreciated. Even alternative methods to display rounded / circle images on a pdf are welcome (I already tried html2canvas and that didn't work).

Any info on why clearRect is causing page wide faults when referenced in code path? codepen for reference

I am trying to create a 'hangman' display for my hangman game with the HTML canvas element. I got the hangman to display one step at a time but I can't seem to clear the canvas (was expecting it to be the easier step...). When I add the clearRect call it causes my whole page to fault out. Can't start the game etc - even when I call it only at the end of a game...
Any advice would be appreciated - new to the web world so assuming I'm doing something silly :)
See the following code pen for the source files and a display of the issue:
https://codepen.io/enewmanMN/pen/LYPWpQq
Tried moving the clearRect call around to avoid calling it right away to see if I could even get the game started with it in the code path but not having any luck.
https://codepen.io/enewmanMN/pen/LYPWpQq
function clearCanvas () {
myStickman = document.getElementById("stickman");
context = myStickman.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height); //CAUSING FAULTS
context.beginPath();
context.strokeStyle = "#fff";
context.lineWidth = 2;
}
Was expecting it to clear the canvas element 'stickman' but instead loose functionality to the page.
When I ran your code with the clearRect uncommented, I got an error saying canvas is not defined. You gave the canvas the name myStickman. This fixed it
context.clearRect(0, 0, myStickman.width, myStickman.height);

Canvas - lines drawn but not showing up in google inspect element

I'm new to using canvas and am having a weird issue. My canvas lines are successfully being drawn using:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
where canvas is the id of a canvas. I then draw using the methods:
context.strokeStyle = "red";
context.beingPath();
context.moveTo(x, y);
context.lineTo(x, y);
context.stroke();
with lineTo being called in a loop updating its position. I use these methods in a function and can draw multiple lines. The issue is (is it an issue?) when I use google's inspect elements I can't find these lines under the canvas that was created. I am used to seeing a path element of some sort.
I can see the script that created these lines, however.
EDIT: just checked another website using canvas and this seems to be normal behavior. Would like confirmation though.
Thanks
Yes It's normal behaviour.
In 2012 the chrome have some experimental plugin with help inspect canvas. But I not sure if it still avaiable (I found information here http://www.html5rocks.com/en/tutorials/canvas/inspection/)

Visualizing html5 canvas

This may be off topic but I'm not sure where else to go with this question. I'm just getting started with HTML5 canvas element and all of the incredibly powerful things it can do. I was hoping someone could offer some advise. When working with custom paths and bezier curves, what is the easiest/best way to visualize where the points belong on the canvas to achieve a desired effect. Right now it feels like I'm just guessing plotting points in any place hoping to end up with the right angle/shape that I want.
To be more specific I want to create a shape that will act as an image mask, and will later need to animate this shape. Much like this fiddle http://jsfiddle.net/jimrhoskins/dDUC3/1/ (someone else's work) but since I can't see where the picture is on the canvas or where any of the points are, I'm really just guessing at the approximate shape I need to make. I'm just wondering if there's a better way, or some function in javascript that can map the location of an image and give me at least a better place to start.
Here is what I know/have tried already
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
// Save the state, so we can undo the clipping
context.save();
// Create a shape, of some sort
context.beginPath();
context.moveTo(somex, somey);
context.bezierCurveTo(somexstart, someystart, somexcontrol, someycontro, somexend, someyend);
context.arcTo(somecoordinates);
context.closePath();
// Clip to the current path
context.clip();
context.drawImage(img, 0, 0);
// Undo the clipping
context.restore();
}
// Specify the src to load the image
img.src = "url";
How about opening the image in an SVG editor. Drawing a path on a layer above the image. Then open the SVG and copy the coordinates?
Try an SVG Editor. You can get the points there. You can add images too. SVG animation is used nowadays as well. If you have Adobe Illustrator, it will be easier to draw there and just save it as SVG.

HTML5 Canvas DrawImage method

I am using 'drawImage()' method of HTML5 in my JS file to draw an image in screen. But the image is not getting displayed in screen. I am using the following codes. I dont understand what wrong am I doing here.No errors found on console.
It would be so great if anybody can help me..
Code to draw Image(failed)
=========================
var image = new Image();
image.onload = function() {
console.log("Image has loaded");
// body.appendChild(image);
ctx.drawImage(image,leftStart,areaBox.top+height/4,20, height/2);
};
image.src = "/MyProject/resources/base/images/close.png";
Also I could draw rectangle box using strokeRect()method.
Code to draw rectangle (success)
================================
ctx.strokeRect(leftStart, areaBox.top + height/4, 20, height/2);
leftStart is X co-ordinate. (areaBox.top + height/4) is the Y co-ordinate. Last two params are the width and height.
leftStart: 1500
areaBox.top: 39
height: 45
Your code for loading the image an drawImage is fine as long as your x,y,width,height parameters of drawImage are valid. So double-check your parameters to drawImage for validity.
In particular I see you use areaBox.top but you don't use areaBox.height--just height.

Categories