I'm facing a dilemma with my HTML code:
<div id=test>
<canvas id="pic" width="300" height="250"></canvas>
</div>
Whenever I attempt to adjust the width and height using CSS (by removing the width and height attributes from the HTML element) like so:
#pic{
width:300px;
height:250px;
}
The image ends up being stretched - why is this happening?
When I add additional CSS properties to the div
, such as:
#test{
float:right;
border:solid red;
border-radius: 10px;
box-shadow: 5px 5px 20px #888;
}
The canvas aligns tightly to the top left corner, and for some reason, the border created around the canvas appears slightly larger than the canvas itself.
I've tried various adjustments with margins and padding to move the canvas inside the "box," but have been unsuccessful in achieving the desired alignment.
Is there a way to center the canvas within the "box" or alternatively reduce the size of the box?
New Addition
To address the initial issue, here's the complete code snippet:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function myImage() {
var context = document.getElementById('pic').getContext('2d');
var img = new Image();
img.src = "saturn-400x300.jpg";
img.onload = function () {
context.drawImage(img, 0, 0, 300, 250);
}
}
</script>
<style>
#pic {
width:300px;
height:250px;
}
</style>
</head>
<body onload="myImage()">
<div id="test">
<canvas id="pic" width="300" height="250"></canvas>
</div>
</body>
</html>
With the current setup utilizing inline attributes, the image appears fine. Here's how it looks:
https://i.sstatic.net/wENX4.jpg
However, upon removing the inline attributes and retaining only the styles, the layout appears like this:
https://i.sstatic.net/KC9HZ.jpg
Regarding the secondary issue, I retained the inline attributes for explanation purposes. I added the following code to the style tag of the div
:
#test{
float:right;
border:solid red;
border-radius: 10px;
box-shadow: 5px 5px 20px #888;
}
The gap between the red border and the canvas is what I am trying to minimize.