我正在尝试绘制图像的一部分,但它无法正常工作。 当我尝试使用它时,宽度和高度与原始不一样。
这是我的代码
window.onload = function() {
ImageObjSketch = new Image(); // URL
ImageObjSketch.src = 'https://i.imgur.com/75lATF9.png';
canvasClone = document.getElementById("squareTarget");
ctxClone = canvasClone.getContext("2d");
ctxClone.drawImage(ImageObjSketch,34,119,16,16,0,0,38,38);
}
#squareTarget {
width: 38px; height: 38px;
position: relative;
right: 0px;
display: inline-block;
border: 1px #000000 solid;
}
<canvas id="squareTarget"></canvas>
你可以看到它与方形不成比例,虽然我设定了正方形的全尺寸。
另一个问题,你可以看到你必须运行这个代码两次以查看图像,为什么会这样?
答案 0 :(得分:0)
您需要明确指定画布的大小。 然后你可以获得2d Context:
public ActionResult Save(PropertySelling property)
{
if (!ModelState.IsValid)
{
var viewModel = new NewPropertyViewModel()
{
PropertySelling = property,
Sellers = _context.Sellers.ToList()
};
return View("PropertyForm", viewModel);
}
if (property.PropertySellingId == 0)
_context.PropertySellings.Add(property);
else
{
var propertyInDb = _context.PropertySellings.SingleOrDefault(p => p.PropertySellingId == property.PropertySellingId);
propertyInDb.Street = property.Street;
propertyInDb.City = property.City;
propertyInDb.Postcode = property.Postcode;
propertyInDb.Type = property.Type;
propertyInDb.SellingPrice = property.SellingPrice;
propertyInDb.ViewingStartDate = property.ViewingStartDate;
propertyInDb.ViewingEndDate = property.ViewingEndDate;
propertyInDb.NearbyAnementies = property.NearbyAnementies;
}
_context.SaveChanges();
return RedirectToAction("Index", "Properties");
}
然后你的尺寸是38,但你应该使用文件的高度和宽度,但这是一个重构。
类似的东西:
window.onload = function() {
var ImageObjSketch = new Image(); // URL
ImageObjSketch.src = 'https://i.imgur.com/75lATF9.png';
var canvasClone = document.getElementById("squareTarget");
canvasClone.width = 38;
canvasClone.height = 38;
ctxClone = canvasClone.getContext("2d");
ctxClone.drawImage(ImageObjSketch, 34,119,16,16,0,0,38,38);
}