using local fonts in drawing html5 canvas text - html

I'm trying to build a simple tool like meme generator using HTML5 canvas. Is it possible to use local fonts on the mobile phone (this is target towards mobile) in the canvas?

#Akxe correctly answers that you can .fillText using local fonts to draw on html5 canvas.
It's also common to pull necessary font(s) from various internet font hosts.
Here's an example of how to download a web font & draw with it on html5 canvas:
// load google font == Monoton
WebFontConfig = {
google:{ families: ['Monoton'] },
active: function(){start();},
};
(function(){
var wf = document.createElement("script");
wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js';
wf.async = 'true';
document.head.appendChild(wf);
})();
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
function start(){
ctx.font = '40px Monoton';
ctx.textBaseline = 'top';
ctx.fillText('Monoton Font', 20, 10);
var width=ctx.textMetrics('No').width;
console.log(width);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<h4>"Monoton" font drawn on canvas is a downloaded web font</h4>
<canvas id="canvas" width=400 height=100></canvas>

You can specify any font to the canvas. You should be able to type anything that CSS would accept
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "Arial 30px";

Related

draw svg file on html canvas programmatically

I've been having some trouble drawing an svg onto a canvas with javascript. I would like this to work...
HTML
<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px" />
Javascript
function drawHandCanvas(){
var canvas = document.getElementById('handCanvas');
var ctx = canvas.getContext('2d');
var img= document.createElement('img');
img.src='images/handCursor.svg';
img.width = 60; img.height = 60;
ctx.drawImage(img,0,0);
}
drawHandCanvas();
But it doesn't.
If I add an SVG element I can get this to work.
HTML
<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px" />
<img id="handSVG" src="images/handCursor.svg"/>
Javascript
function drawHandCanvas(){
var canvas = document.getElementById('handCanvas');
var ctx = canvas.getContext('2d');
var img=document.getElementById('handSVG');
img.width = 60; img.height = 60;
setTimeout(function(){
ctx.drawImage(img,0,0);
img.hidden='true';
}, 10);
}
drawHandCanvas();
Note that in this 2nd method of doing it I have to use a setTimeout method to get it to work and add an img element at the end of my down, which I hide after drawing on the canvas. Super hacky! If I just use window.onload instead of setTimeout, it doesn't work. It will hide img, but the drawImage() does nothing, presumably because the canvas isn't ready when the window is already done loading. Any thoughts?
I don't have your svg file, but that being said you have to typically wait till the image is loaded before it will load to canvas. It is like drawing something that isn't there. I think this should work for you.
function drawHandCanvas(){
var canvas = document.getElementById('handCanvas');
var ctx = canvas.getContext('2d');
var img= document.createElement('img');
img.onload = function(){
ctx.drawImage(this,0,0);
}
img.src='images/handCursor.svg';
img.width = 60; img.height = 60;
}
drawHandCanvas();

How to use Data URI to copy canvas as image or another canvas

I converted an image to canvas and made changes to it and want to convert the canvas with changes to a Data URI and use that for the source of image object or another canvas
I am using the following code to do so but do not get any results. Please suggest any other approach I can use.
Code:
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('testImage'); //image object
var canvas = document.getElementById('canvasPnl');// source canvas
var context= canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0,300,300 );
context.fillStyle="#FFFFFF";
context.fillText('Latitude:'+ lat.toString()+'Longitude:'+ lon.toString(),0,10);
context.fillText(new Date(), 0, 20);
context.save();
};
imageObj.src=imageURI;
var img_uri= canvas.toDataURL("image/png");
var image = new Image();
image.src =img_uri;
largeImage.src=img_uri;
var canvas2 = document.getElementById('canvasPnl2');//destination canvas
var context2= canvas2.getContext("2d");
context2.drawImage(image,0,0);
}
You've almost got it.
Since you’re generating a second image object (var image), you must also do a second onload:
var imageObj = new Image();
imageObj.onload = function(){
...
var image = new Image();
image.onload=function(){
...
}
image.src=canvas.toDataURL(); // .png is the default
};
imageObj.crossOrigin="anonymous";
imageObj.src=imageURI;
Also, you have a context.save in there without a context.restore (usually they are paired).
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/ne4Up/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px; }
canvas{border:1px solid red;}
img{border:1px solid blue;}
</style>
<script>
$(function(){
var lat="lat";
var lon="long";
onPhotoURISuccess("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png");
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('testImage'); //image object
var canvas = document.getElementById('canvasPnl');// source canvas
var context= canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0,100,100 );
context.fillStyle="#FFFFFF";
context.fillText('Latitude:'+ lat.toString()+'Longitude:'+ lon.toString(),0,10);
context.fillText(new Date(), 0, 20);
// context.save(); // where's the matching context.restore();
var image = new Image();
image.onload=function(){
var canvas2 = document.getElementById('canvasPnl2');//destination canvas
var context2= canvas2.getContext("2d");
context2.drawImage(image,0,0);
largeImage.src=canvas2.toDataURL();
}
image.src=canvas.toDataURL(); // .png is the default
};
imageObj.crossOrigin="anonymous";
imageObj.src=imageURI;
}
}); // end $(function(){});
</script>
</head>
<body>
<p>Pnl</p>
<canvas id="canvasPnl" width=100 height=100></canvas>
<p>Pnl2</p>
<canvas id="canvasPnl2" width=100 height=100></canvas>
<p>testImage</p>
<img id=testImage src="houseicon.png" width=100 height=100 >
</body>
</html>
If you simply want to draw a canvas onto another canvas there is no need to convert it to image first. Just use the source canvas directly as an argument to drawImage:
context2.drawImage(canvas, 0, 0);
If you absolutely want to convert it to image first you only need to modify a few lines to handle the asynchronous nature of image loading:
var img_uri= canvas.toDataURL("image/png");
var image = new Image();
var canvas2; /// put them here so they are available outside onload below
var context2;
/// put it in a onload here as well
image.onload = function() {
canvas2 = document.getElementById('canvasPnl2');//destination canvas
context2= canvas2.getContext("2d");
context2.drawImage(image,0,0);
}
image.src =img_uri;
A small note: some versions of Chrome has a bug with new Image. For this reason consider using document.createElement('image') instead.

Use image for background of canvas

I am making the simple canvas application.
I want to use image for background of canvas.
I have found out that I should use drawImage(img,x,y).
This is my codes ,but drummap.img doesn't appear.
Where is wrong?
Test
<canvas id="leap-overlay"></canvas>
<script src="leap.js"></script>
<script>
var canvas = document.getElementById("leap-overlay");
// fullscreen
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
// create a rendering context
var ctx = canvas.getContext("2d");
ctx.translate(canvas.width/2,canvas.height);
var img = new Image();
img.src = "drummap.jpg";
ctx.drawImage(img,0,0,100,100);
Assuming that your image drummap.jpg is located in said directory, create the image, set the onload to use the new image, and then set the src (see):
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0, 100, 100);
};
img.src = 'drummap.jpg';
I'm not sure how you're clearing your canvas or what your drawing, but remember your canvas is inherently transparent so feel free to give the canvas a css style background:
<canvas style = "background-image: url(pathtoyourimage.jpg);"></canvas>
Hope that helps.

Base64 PNG data to HTML5 canvas

I want to load a PNG image encoded in Base64 to canvas element. I have this code:
<html>
<head>
</head>
<body>
<canvas id="c"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
ctx.drawImage(data, 0, 0);
</script>
</body>
</html>
In Chrome 8 I get the error: Uncaught TypeError: Type error
And in Firefox's Firebug this: "The type of an object is incompatible with the expected type of the parameter associated to the object" code: "17"
In that base64 is 5x5px black PNG square that I have made in GIMP and turn it to base64 in GNU/Linux's program base64.
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
<canvas id="c"></canvas>
I've tried it in chrome and it works fine.
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can
be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
....

Drawing an SVG file on a HTML5 canvas

Is there a default way of drawing an SVG file onto a HTML5 canvas? Google Chrome supports loading the SVG as an image (and simply using drawImage), but the developer console does warn that resource interpreted as image but transferred with MIME type image/svg+xml.
I know that a possibility would be to convert the SVG to canvas commands (like in this question), but I'm hoping that's not needed. I don't care about older browsers (so if FireFox 4 and IE 9 will support something, that's good enough).
EDIT: Dec 2019
The Path2D() constructor is supported by all major browsers now, "allowing path objects to be declared on 2D canvas surfaces".
EDIT: Nov 2014
You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers (75% coverage: Chrome, IE11, and Safari work, Firefox works with some bugs, but nightly has fixed them).
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg> element inserted into the DOM for reference.
You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:
var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);
Live example of that here.
Original 2010 answer:
There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.
I'd suggest looking in to canvg: (check homepage & demos)
canvg takes the URL to an SVG file, or the text of the SVG file, parses it in JavaScript and renders the result on Canvas.
Further to #Matyas answer: if the svg's image is also in base64, it will be drawn to the output.
Demo:
var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;
// set it as the source of the img element
img.onload = function() {
// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);
}
img.src = image64;
svg, img, canvas {
display: block;
}
SVG
<svg height="40" width="40">
<rect width="40" height="40" style="fill:rgb(255,0,255);" />
<image xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAEX0lEQVQ4jUWUyW6cVRCFv7r3/kO3u912nNgZgESAAgGBCJgFgxhW7FkgxAbxMLwBEmIRITbsQAgxCEUiSIBAYIY4g1EmYjuDp457+Lv7n+4tFjbwAHVOnVPnlLz75ht67OhhZg/M0p6d5tD9C8SNBBs5XBJhI4uNLC4SREA0UI9yJr2c4e6QO+v3WF27w+rmNrv9Pm7hxDyHFg5yYGEOYxytuRY2SYiSCIwgRgBQIxgjEAKuZWg6R9S0SCS4qKLZElY3HC5tp7QPtmlMN7HOETUTXBJjrEGsAfgPFECsQbBIbDGJZUYgGE8ugQyPm+o0STtTuGZMnKZEjRjjLIgAirEOEQEBDQFBEFFEBWLFtVJmpENRl6hUuFanTRAlbTeZarcx0R6YNZagAdD/t5N9+QgCYAw2jrAhpjM3zaSY4OJGTDrVwEYOYw2qioigoviq5MqF31m9fg1V5fCx+zn11CLNVnufRhBrsVFE1Ihpthu4KDYYwz5YQIxFBG7duMZnH31IqHL6wwnGCLFd4pez3/DaG2/x4GNPgBhEZG/GGlxkMVFkiNMYay3Inqxed4eP33uf7Y0uu90xWkGolFAru7sZn5w5w921m3u+su8vinEO02hEWLN/ANnL2rkvv2an2yd4SCKLM0JVBsCgAYZZzrnPP0eDRzXgfaCuPHXwuEYjRgmIBlQVVLl8/hKI4fRzz3L6uWe5+PMvnHz6aa4uX+D4yYe5vXaLH86eoyoLjLF476l9oKo9pi5HWONRX8E+YznOef7Vl1h86QWurlwjbc+QpikPPfoIcZLS39pmMikp8pzae6q6oqgriqrGqS+xeLScoMYSVJlfOMTl5RXW1+5w5fJVnFGWf1/mxEMnWPppiclkTLM5RdJoUBYFZVlQ5DnZMMMV167gixKLoXXsKGqnOHnqOJ/+/CfZ+XUiZ0jTmFv5mAvf/YjEliQ2vPD8Ir6qqEcZkzt38cMRo5WruFvfL9FqpyRxQhj0qLOax5I2S08+Tu/lFiGUGOPormxwuyfMnjrGrJa88uIixeYWl776lmrzNjmw8vcG8sU7ixpHMXFsCUVg9tABjEvRgzP82j7AhbyiX5Qcv2+Bvy7dYGZ1k7efeQB/Y4PBqGBtdYvb3SFzLcfqToZc/OB1zYeBSpUwLBlvjZidmWaSB1yaYOfn6LqI/r0hyU6P+cRSlhXjbEI2zvnt7y79oqQ3qeg4g6vKjCIXehtDmi6m0UnxVnCRkPUHVNt9qkLJxgXOCYNOg34v48raPaamU2o89/KKsQ9sTSpc0JK7NwdcX8s43Ek5cnSOLC/Z2R6Rj0ra0w2W1/t0xyWn51uk2Ri1QtSO6OU5d7OSi72cQeWxKG7p/Dp//JXTy6C1Pcbc6DMpPRtjTxChEznWhwVZUCKrjCrPoPDczHLmnLBdBgZlRRWUEBR3ZKrme5TlrTGlV440Y1IrXM9qQGi6mkG5V6uza7tUIeCDElTZ1L26elX+fcH/ACJBPYTJ4X8tAAAAAElFTkSuQmCC" height="20px" width="20px" x="10" y="10"></image></svg><br/>
IMAGE
<img/><br/>
CANVAS
<canvas></canvas><br/>
You can easily draw simple svgs onto a canvas by:
Assigning the source of the svg to an image in base64 format
Drawing the image onto a canvas
Note: The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)
Demonstration:
(Note that the embedded image is only visible in the svg)
var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;
// set it as the source of the img element
img.src = image64;
// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);
svg, img, canvas {
display: block;
}
SVG
<svg height="40">
<rect width="40" height="40" style="fill:rgb(255,0,255);" />
<image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>
</svg>
<hr/><br/>
IMAGE
<img/>
<hr/><br/>
CANVAS
<canvas></canvas>
<hr/><br/>
Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"
As Simon says above, using drawImage shouldn't work. But, using the canvg library and:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);
This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.
Something to add, to show the svg correctly in canvas element add the attributes height and width to svg root element, Eg:
<svg height="256" width="421">...</svg>
Or
// Use this if to add the attributes programmatically
const svg = document.querySelector("#your-svg");
svg.setAttribute("width", `${width}`);
svg.setAttribute("height", `${height}`);
For more details see this
As vector graphics are meant to be potentially scaled, I will offer a method I have made that is as similar to SVG as possible. This method supports:
A resizable canvas
Transparency
Hi-resolution graphics (automatically, but no pinch support yet)
Scaling of the SVG in both directions! (To do this with pixels, you will have to divide the new length by the old one)
This is done by converting the SVG to canvas functions here, then adding that to svgRed() (after changing the name of ctx to ctx2. The svgRed() function is used on startup and during pixel ratio changes (for example, increasing the zoom), but not before the canvas is scaled (in order to increase the size of the image). It converts the result into an Image, and can be called any time by ctx.drawImage(redBalloon, Math.round(Math.random() * w), Math.round(Math.random() * h)). To clear the screen, use ctx.clearRect(0, 0, w, h) to do so.
Testing this with the SVG, I found that this is many times faster, as long as the zoom is not set to large values (I discovered that a window.devicePixelRatio of 5 gives just over twice the speed as an SVG, and a window.devicePixelRatio of 1 is approximately 60 times faster).
This also has the bonus benefit of allowing many "fake SVG" items to exist simultaneously, without messing with the HTML (this is shown in the code below). If the screen is resized or scaled, you will need to render it again (completely ignored in my example).
The canvas showing the result is scaled down (in pixels) by the devicePixelRatio, so be careful when drawing items! Scaling (with ctx.scale() this canvas will result in a potentially blurry image, so be sure to account for the pixel difference!
NOTE: It seems that the browser takes a while to optimize the image after the devicePixelRatio has changed (around a second sometimes), so it may not be a good idea to spam the canvas with images immediately, as the example shows.
<!DOCTYPE html>
<html>
<head lang="en">
<title>Balloons</title>
<style>
* {
user-select: none;
-webkit-user-select: none;
}
body {
background-color: #303030;
}
</style>
</head>
<body>
<canvas id="canvas2" style="display: none" width="0" height="0"></canvas>
<canvas id="canvas"
style="position: absolute; top: 20px; left: 20px; background-color: #606060; border-radius: 25px;" width="0"
height="0"></canvas>
<script>
// disable pinches: hard to implement resizing
document.addEventListener("touchstart", function (e) {
if (e.touches.length > 1) {
e.preventDefault()
}
}, { passive: false })
document.addEventListener("touchmove", function (e) {
if (e.touches.length > 1) {
e.preventDefault()
}
}, { passive: false })
// disable trackpad zooming
document.addEventListener("wheel", e => {
if (e.ctrlKey) {
e.preventDefault()
}
}, {
passive: false
})
// This is the canvas that shows the result
const canvas = document.getElementById("canvas")
// This canvas is hidden and renders the balloon in the background
const canvas2 = document.getElementById("canvas2")
// Get contexts
const ctx = canvas.getContext("2d")
const ctx2 = canvas2.getContext("2d")
// Scale the graphic, if you want
const scaleX = 1
const scaleY = 1
// Set up parameters
var prevRatio, w, h, trueW, trueH, ratio, redBalloon
function draw() {
for (var i = 0; i < 1000; i++) {
ctx.drawImage(redBalloon, Math.round(Math.random() * w), Math.round(Math.random() * h))
}
requestAnimationFrame(draw)
}
// Updates graphics and canvas.
function updateSvg() {
var pW = trueW
var pH = trueH
trueW = window.innerWidth - 40
trueH = Math.max(window.innerHeight - 40, 0)
ratio = window.devicePixelRatio
w = trueW * ratio
h = trueH * ratio
if (trueW === 0 || trueH === 0) {
canvas.width = 0
canvas.height = 0
canvas.style.width = "0px"
canvas.style.height = "0px"
return
}
if (trueW !== pW || trueH !== pH || ratio !== prevRatio) {
canvas.width = w
canvas.height = h
canvas.style.width = trueW + "px"
canvas.style.height = trueH + "px"
if (prevRatio !== ratio) {
// Update graphic
redBalloon = svgRed()
// Set new ratio
prevRatio = ratio
}
}
}
window.onresize = updateSvg
updateSvg()
draw()
// The vector graphic (you may want to manually tweak the coordinates if they are slightly off (such as changing 25.240999999999997 to 25.241)
function svgRed() {
// Scale the hidden canvas
canvas2.width = Math.round(44 * ratio * scaleX)
canvas2.height = Math.round(65 * ratio * scaleY)
ctx2.scale(ratio * scaleX, ratio * scaleY)
// Draw the graphic
ctx2.save()
ctx2.beginPath()
ctx2.moveTo(0, 0)
ctx2.lineTo(44, 0)
ctx2.lineTo(44, 65)
ctx2.lineTo(0, 65)
ctx2.closePath()
ctx2.clip()
ctx2.strokeStyle = '#0000'
ctx2.lineCap = 'butt'
ctx2.lineJoin = 'miter'
ctx2.miterLimit = 4
ctx2.save()
ctx2.beginPath()
ctx2.moveTo(0, 0)
ctx2.lineTo(44, 0)
ctx2.lineTo(44, 65)
ctx2.lineTo(0, 65)
ctx2.closePath()
ctx2.clip()
ctx2.save()
ctx2.fillStyle = "#e02f2f"
ctx2.beginPath()
ctx2.moveTo(27, 65)
ctx2.lineTo(22.9, 61.9)
ctx2.lineTo(21.9, 61)
ctx2.lineTo(21.1, 61.6)
ctx2.lineTo(17, 65)
ctx2.lineTo(27, 65)
ctx2.closePath()
ctx2.moveTo(21.8, 61)
ctx2.lineTo(21.1, 60.5)
ctx2.bezierCurveTo(13.4, 54.2, 0, 41.5, 0, 28)
ctx2.bezierCurveTo(0, 9.3, 12.1, 0.4, 21.9, 0)
ctx2.bezierCurveTo(33.8, -0.5, 45.1, 10.6, 43.9, 28)
ctx2.bezierCurveTo(43, 40.8, 30.3, 53.6, 22.8, 60.2)
ctx2.lineTo(21.8, 61)
ctx2.fill()
ctx2.stroke()
ctx2.restore()
ctx2.save()
ctx2.fillStyle = "#f59595"
ctx2.beginPath()
ctx2.moveTo(18.5, 7)
ctx2.bezierCurveTo(15.3, 7, 5, 11.5, 5, 26.3)
ctx2.bezierCurveTo(5, 38, 16.9, 50.4, 19, 54)
ctx2.bezierCurveTo(19, 54, 9, 38, 9, 28)
ctx2.bezierCurveTo(9, 17.3, 15.3, 9.2, 18.5, 7)
ctx2.fill()
ctx2.stroke()
ctx2.restore()
ctx2.restore()
ctx2.restore()
// Save the results
var image = new Image()
image.src = canvas2.toDataURL()
return image
}
</script>
</body>
</html>
Try this:
let svg = `<svg xmlns="http://www.w3.org/2000/svg" ...`;
let blob = new Blob([svg], {type: 'image/svg+xml'});
let url = URL.createObjectURL(blob);
const ctx = canvas.getContext('2d');
canvas.width = 900;
canvas.height = 1400;
const appLogo = new Image();
appLogo.onload = () => ctx.drawImage(appLogo, 54, 387, 792, 960);
appLogo.src = url;
// let image = document.createElement('img');
// image.src = url;
// image.addEventListener('load', () => URL.revokeObjectURL(url), {once: true});
Note: Blob is not defined in Node.js file, This is code designed to run in the browser, not in Node.
More info here